package com.xtecher.app.column.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.xtecher.app.R;
import com.xtecher.app.column.bean.BannerResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Luhao on 2017/2/25.
 */

public class BannerAdapter extends PagerAdapter {

    private final Context context;
    private final List<BannerResponse> bannerResponses;
    private final List<View> views;

    public BannerAdapter(Context context, List<BannerResponse> bannerResponses) {
        this.context = context;
        this.bannerResponses = bannerResponses;
        LayoutInflater inflater = LayoutInflater.from(context);

        views = new ArrayList<>();
        if (bannerResponses.size() == 0)
            return;
        if (bannerResponses.size() == 1) {
            View inflate = inflater.inflate(R.layout.item_banner, null);
            views.add(inflate);
        } else {
            for (int i = 0; i < bannerResponses.size() + 2; i++) {
                View inflate = inflater.inflate(R.layout.item_banner, null);
                views.add(inflate);
            }
        }
    }

    @Override
    public int getCount() {
        return bannerResponses.size() > 1 ? bannerResponses.size() + 2 : 1;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = views.get(position);
        ImageView imgAd = (ImageView) view.findViewById(R.id.img_banner);
        if (position == 0) {
            position = bannerResponses.size() - 1;
            Glide.with(container.getContext())
                    .load(bannerResponses.get(position).getImage())
                    .placeholder(R.drawable.banner)
                    .error(R.drawable.banner)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgAd);
        } else if (position == bannerResponses.size() + 1) {
            position = 0;
            Glide.with(container.getContext())
                    .load(bannerResponses.get(position).getImage())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgAd);
        } else {
            position = position - 1;
            Glide.with(container.getContext())
                    .load(bannerResponses.get(position).getImage())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgAd);
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
